package com.xckj.cycling.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.xckj.cycling.R;
import com.xckj.cycling.databinding.ActivityBrowserBinding;
import com.xckj.cycling.event.EventUploadAvatar;
import com.xckj.cycling.framework.BaseActivity;
import com.xckj.cycling.global.Constant;
import com.xckj.cycling.utils.NotificationUtil;
import com.xckj.cycling.view.CWebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;


/**
 * @Author: ChenYao
 * @Describe: 浏览器页面
 * @Date: 2023/3/18 21:16
 */
public class BrowserActivity extends BaseActivity<ActivityBrowserBinding> {
    public static void start(Context context, String path) {
        Intent i = new Intent(context, BrowserActivity.class);
        i.putExtra("path", path);
        context.startActivity(i);
    }

    private String path;
    private CWebView webView;

    @Override
    protected int loadLayout() {
        return R.layout.activity_browser;
    }

    @Override
    protected void setTitle() {
        super.setTitle();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe
    public void event(EventUploadAvatar eventUploadAvatar) {
        webView.getMAgentWeb().getUrlLoader().reload();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        path = getIntent().getStringExtra("path");
        initWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webView = dataBinding.webView;
        String url = null;
        if (path.startsWith("http")) {
            url = path;
        } else {
            url = Constant.WEB_URL + path;
        }
        webView.setHorizontalScrollBarEnabled(false);
        webView.loadUrl(url);
    }


    @Override
    public void onClick(View view) {

    }

    @Override
    public void onBackPressed() {
        if (webView.goBack()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            boolean open = NotificationUtil.isNotificationEnabled(this);
            String param = open ? "1" : "0";
            String url = "javascript:getNotice('" + param + "')";
            Log.d("onResume", "url = " + url);
            webView.loadUrl(url);
        }
    }
}
